package com.me.bbs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.me.bbs.common.SessionUtils;
import com.me.bbs.dto.PostCollectionDTO;
import com.me.bbs.entity.Post;
import com.me.bbs.entity.PostCollection;
import com.me.bbs.entity.PostLike;
import com.me.bbs.mapper.CollectionMapper;
import com.me.bbs.service.ICollectionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.me.bbs.service.IPostService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lm
 * @since 2023-01-16
 */
@Service
public class CollectionServiceImpl extends ServiceImpl<CollectionMapper, PostCollection> implements ICollectionService {
    @Resource
    IPostService postService;
    @Resource
    CollectionMapper collectionMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveCollection(Long postId) throws Exception {
        Long uid = (Long) SessionUtils.getAttribute("user");
        PostCollection postCollection = this.lambdaQuery()
                .eq(PostCollection::getUser, uid)
                .eq(PostCollection::getPost, postId)
                .one();
        if (postCollection != null) return;
        postCollection = new PostCollection();
        postCollection.setPost(postId);
        postCollection.setUser(uid);
        boolean save = this.save(postCollection);
        if(!save)
            throw new Exception("保存状态异常");
        postService.lambdaUpdate()
                .eq(Post::getPostId, postId)
                .setSql("collect_count = collect_count + 1")
                .update();

    }

    @Override
    public void delCollection(Long postId) throws Exception {
        Long uid = (Long) SessionUtils.getAttribute("user");
        boolean remove = this.lambdaUpdate()
                .eq(PostCollection::getUser, uid)
                .eq(PostCollection::getPost, postId)
                .remove();
        if(!remove)
            throw new Exception("重复请求");
        postService.lambdaUpdate()
                .eq(Post::getPostId, postId)
                .setSql("collect_count = collect_count - 1")
                .update();
    }

    @Override
    public Page<PostCollectionDTO> getCollectionByUser(Page<PostCollectionDTO> page, LambdaQueryWrapper<PostCollection> wrapper) {
        return collectionMapper.listCollection(page, wrapper);
    }
}
